<?php

namespace App\Console\Commands;

use App\Models\Common\Wechat;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class RedpackExpired extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:redpack_expired';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '查询红包过期';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        // 查询红包发送记录表中未接收的红包信息
        $mch_billnos = DB::table('explore_settlement')
            ->where('received', '=', 0)
//            ->where('created_at', '>=', date('Y-m-d H:i:s', strtotime("-1 day")))
            ->pluck('mch_billno')
            ->toArray();

        // 如果没有待检查的红包结束
        if (!count($mch_billnos)) return;

        $payment = Wechat::payment();
        $redpack = $payment->redpack;

        foreach ($mch_billnos as $mch_billno) {
            $info = $redpack->info($mch_billno);
            Log::debug('红包查询结果',$info);
            // 处理异常
            if ($info['err_code'] !== 'SUCCESS') {
                DB::table('explore_settlement')->where('mch_billno', '=', $mch_billno)->update([
                    'received' => 2,
                    'reason' => $info['err_code'] . ':' . $info['err_code_des'],
                ]);
                Log::error(RedpackExpired::class, $info);
                continue;
            }

            switch ($info['status']) {
                case 'RECEIVED': // 已领取
                    DB::table('explore_settlement')->where('mch_billno', '=', $mch_billno)->update([
                        'received' => 1,
                        'rcv_time' => $info['hblist']['hbinfo']['rcv_time'],
                    ]);
                    break;
                case 'FAILED': // 领取失败
                case 'RFUND_ING':
                case 'REFUND':
                    DB::table('explore_settlement')->where('mch_billno', '=', $mch_billno)->update([
                        'received' => 2,
                        'reason' => $info['status'],
                    ]);
                    break;
                case 'SENDING':
                case 'SENT':
                    break;
            }
        }
        return;

    }
}
